import logging
from logging.handlers import RotatingFileHandler
import os

class LogManager:
    _instance = None

    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = super(LogManager, cls).__new__(cls, *args, **kwargs)
            cls._instance._initialize_logger()
        return cls._instance

    def _initialize_logger(self):
        # 获取日志目录路径
        log_dir = 'Log'
        if not os.path.exists(log_dir):
            os.makedirs(log_dir)

        # 配置日志记录器
        self.logger = logging.getLogger('Agenet_logger')
        self.logger.setLevel(logging.DEBUG)

        # 创建一个RotatingFileHandler，设置日志文件大小和备份数量
        file_handler = RotatingFileHandler(
            os.path.join(log_dir, 'app.log'),
            maxBytes=1024 * 1024 * 5,  # 5MB
            backupCount=5,
            encoding='utf-8'
        )
        file_handler.setLevel(logging.DEBUG)

        # 创建一个StreamHandler，用于输出到控制台
        console_handler = logging.StreamHandler()
        console_handler.setLevel(logging.INFO)

        # 定义日志格式
        formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        file_handler.setFormatter(formatter)
        console_handler.setFormatter(formatter)

        # 将处理器添加到日志记录器
        self.logger.addHandler(file_handler)
        self.logger.addHandler(console_handler)

    def get_logger(self):
        return self.logger

# 单例实例化
log_manager = LogManager()